package chatroom;

import chatroom.bean.LoginUser;
import constutil.Constants;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;

/**
 * @Author Gong
 * @Description
 * @dATE 2022/4/18 16:37
 **/
@WebServlet("/loginServlet")  //不能重名
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String[] k1s = req.getParameterValues("k1");
        System.out.println(k1s);
        if(null != username){
            //登录成功
            //跳转到聊天主页
            HttpSession session = req.getSession(true);
            session.setAttribute(Constants.SESSION_USER_ID,username);//登录成功

            //讲登录信息存入ServletContext,其他任意用户就能得到列表信息，多set ,list
            LoginUser loginUser = new LoginUser(username,new Date());


            ServletContext sc = this.getServletContext();
            //
            Set loginUserList = (Set)sc.getAttribute(Constants.LOGIN_USER_LIST);
            if(null == loginUserList){
                loginUserList = new TreeSet();//自动排序
                loginUserList.add(loginUser);
            }else{
                loginUserList.add(loginUser);
            }
            sc.setAttribute(Constants.LOGIN_USER_LIST,loginUserList);


            resp.sendRedirect(req.getContextPath()+"/chatroom/chatroom.jsp");
        }else{

            //如果没有登陆了成功
            //提示用户未成功登录，账号或密码异常
            //TODO
            req.getRequestDispatcher("/index.jsp").forward(req,resp);
        }
    }
}
